package com.zzf.concurrent.example.graceful.interrupt;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/8/5 23:21
 */

@Slf4j
public class GracefulInterruptExample {
    public static void main(String[] args) {
        // flagInterrupt();
        // interruptByInterruptedException();
        interruptByThreadService();
    }

    private static class Worker implements Runnable  {

        private boolean isClose = false;

        public void shutdown() {
            this.isClose = true;
        }

        @Override
        public void run() {
            while (!isClose) {
                log.info("{} -> {}", Thread.currentThread().getName(), System.currentTimeMillis());
            }
        }
    }

    private static void flagInterrupt() {
        Worker worker = new Worker();
        Thread t1 = new Thread(worker);
        t1.start();
        TimeUtil.sleep(3000);
        worker.shutdown();
    }

    private static void interruptByInterruptedException() {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    log.info("{} -> {}", Thread.currentThread().getName(), System.currentTimeMillis());
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        log.info("sleep interrupt!");
                        break;
                    }
                }
            }
        };

        t1.start();
        TimeUtil.sleep(2000);
        t1.interrupt();
    }

    private static void interruptByThreadService() {

        ThreadService threadService = new ThreadService();

        long startTime = System.currentTimeMillis();
        threadService.execute(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        threadService.shutdown(2000);

        threadService.getExecuteThread().interrupt();

        long endTime = System.currentTimeMillis();
        log.info("执行io任务耗时：{}", endTime - startTime);
    }
}
